package vn.ikame.android.boojtran.truyenbua;

import java.util.ArrayList;

import vn.ikame.android.boojtran.truyenbua.download.ItemListDowloadListener;
import vn.ikame.android.boojtran.truyenbua.download.ItemListDownload;
import vn.ikame.android.boojtran.truyenbua.object.GA;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import vn.ikame.android.boojtran.truyenbua.utility.CConstant;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;

public class FunStory extends SuperActivity implements AnimationListener,
		ItemListDowloadListener {
	final Handler myHandler = new Handler();
	private AdView adView;
	private TextView txtFooter, txtTitle, txtContent;
	private Button btnNext;
	private Animation footerAnim;

	// private ViewPager viewPager;
	// private ViewPagerAdapter pagerAdapter;
	// private OnPageChangeListener onPageChange;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.funstory);
		if (funStories == null || funStories.size() <= 0) {
			startActivity(new Intent(FunStory.this, ListItem.class));
			this.finish();
		} else {
			// ((TextView)
			// findViewById(R.id.txt_header)).setVisibility(View.GONE);

			initView();

			// admob
			adView = (AdView) this.findViewById(R.id.adView);
			adView.loadAd(new AdRequest());

			// pagerAdapter = new ViewPagerAdapter();
			// viewPager = (ViewPager) findViewById(R.id.viewpager);
			// viewPager.setAdapter(pagerAdapter);
			// onPageChange = new OnPageChangeListener();
			// viewPager.setOnPageChangeListener(onPageChange);
			// viewPager.setCurrentItem(0);
			initContent();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(new Intent(FunStory.this, ListItem.class));
			FunStory.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onDestroy() {
		if (adView != null) {
			adView.destroy();
		}
		super.onDestroy();
	}

	private void initView() {
		txtFooter = (TextView) findViewById(R.id.txt_footer);
		footerAnim = AnimationUtils.loadAnimation(this, R.anim.anim_footer);
		footerAnim.setAnimationListener(this);
		btnNext = (Button) findViewById(R.id.btn_next);
		txtTitle = (TextView) findViewById(R.id.title);
		txtContent = (TextView) findViewById(R.id.content);
		txtFooter.setText("Nhớ click quảng cáo ủng hộ nha :D");
		// if (viewed % 5 == 0) {
		// txtFooter.setVisibility(View.VISIBLE);
		// txtFooter.startAnimation(footerAnim);
		// }
		btnNext.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				viewed++;
				initContent();
			}
		});
	}

	private void initContent() {
		int i = -1;
		int j = 0;
		int total = funStories.size();
		while (i == -1 || isBelongIntArray(storyArr, funStories.get(i).getId())) {
			if (j == total) {
				i = -1;
				break;
			}
			i = rand(0, total);
			j++;
		}
		if (i == -1) {
			for (int k = 0; k < funStories.size(); k++) {
				if (!isBelongIntArray(storyArr, funStories.get(k).getId())) {
					i = k;
					setContent(k);
				}
			}
			if (i == -1) {
				requestListItems(CConstant.SVR_FUNSTORY_LINK, storyArr.size(),
						itemCount);
			}
		} else {
			setContent(i);
		}
	}

	private void setContent(int index) {
		txtTitle.setText(funStories.get(index).getTitle());
		txtContent.setText(funStories.get(index).getContent());
		storyArr.add(funStories.get(index).getId());
		store.setStoryArr(storyArr);
		if (viewed % 5 == 0) {
			txtFooter.setVisibility(View.VISIBLE);
			txtFooter.startAnimation(footerAnim);
		}
	}

	// private class ViewPagerAdapter extends PagerAdapter {
	// private TextView txtTitle, txtContent;
	//
	// public ViewPagerAdapter() {
	// }
	//
	// @Override
	// public int getCount() {
	// return SuperActivity.totalItem;
	// }
	//
	// @Override
	// public Object instantiateItem(View collection, int pageViewPos) {
	// View view = null;
	// try {
	// LayoutInflater vi = (LayoutInflater) FunStory.this
	// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	// view = vi.inflate(R.layout.funstory, null);
	//
	// txtTitle = (TextView) view.findViewById(R.id.title);
	// txtContent = (TextView) view.findViewById(R.id.content);
	// txtTitle.setText(funStories.get(pageViewPos).getTitle());
	// txtContent.setText(Html.fromHtml(funStories.get(pageViewPos)
	// .getContent()));
	// view.setTag(pageViewPos);
	// ((ViewPager) collection).addView(view, 0);
	// } catch (Exception e) {
	// try {
	// Log.e("TAG", "vvvvvvvvvvvvvvvv");
	// startActivity(new Intent(FunStory.this, ListItem.class));
	// FunStory.this.finish();
	// } catch (Exception ex) {
	// }
	// }
	// return view;
	// }
	//
	// /**
	// * Remove a page for the given position. The adapter is responsible for
	// * removing the view from its container, although it only must ensure
	// * this is done by the time it returns from {@link #finishUpdate()}.
	// *
	// * @param container
	// * The containing View from which the page will be removed.
	// * @param position
	// * The page position to be removed.
	// * @param object
	// * The same object that was returned by
	// * {@link #instantiateItem(View, int)}.
	// */
	// @Override
	// public void destroyItem(View collection, int position, Object view) {
	// ((ViewPager) collection).removeView((View) view);
	// }
	//
	// @Override
	// public boolean isViewFromObject(View view, Object object) {
	// return view == ((View) object);
	// }
	//
	// /**
	// * Called when the a change in the shown pages has been completed. At
	// * this point you must ensure that all of the pages have actually been
	// * added or removed from the container as appropriate.
	// *
	// * @param container
	// * The containing View which is displaying this adapter's
	// * page views.
	// */
	// @Override
	// public void finishUpdate(View arg0) {
	// }
	//
	// @Override
	// public void restoreState(Parcelable arg0, ClassLoader arg1) {
	// }
	//
	// @Override
	// public Parcelable saveState() {
	// return null;
	// }
	//
	// @Override
	// public void startUpdate(View arg0) {
	// }
	//
	// }
	//
	// public class OnPageChangeListener extends
	// ViewPager.SimpleOnPageChangeListener {
	//
	// private int currentPage;
	//
	// @Override
	// public void onPageSelected(int position) {
	// currentPage = position;
	// viewed++;
	// // if (currentPage >= previousTotal - visibleThreshold) {
	// // requestListItems(CConstant.SVR_IMG_LINK, previousTotal,
	// // itemCount);
	// // }
	// // ItemManager.getInstance().setCurItem(position);
	// // if (!isBelongArray(showedArr,
	// // ItemManager.getInstance().getItem(position).getId())) {
	// // showedArr.add(ItemManager.getInstance().getItem(position)
	// // .getId());
	// // store.setShowedArr(showedArr);
	// // }
	// // try {
	// // store.setPic(ItemManager.getInstance().getCurItem().getId());
	// // } catch (Exception e) {
	// // }
	// try {
	// initView();
	// } catch (Exception e) {
	// }
	// System.out.println("current= "
	// + ItemManager.getInstance().getListItem().get(currentPage)
	// .getContent());
	// }
	//
	// public int getCurrentPage() {
	// return currentPage;
	// }
	// }

	@Override
	public void onAnimationEnd(Animation animation) {
		try {
			txtFooter.setVisibility(View.GONE);
		} catch (Exception e) {
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {
	}

	@Override
	public void onAnimationStart(Animation animation) {
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.option_menu, menu);
		MenuItem item = menu.findItem(R.id.funstory);
		item.setTitle("Truyện tranh bựa");
		// menu.removeItem(R.id.funstory);
		menu.removeItem(R.id.refresh);
		menu.removeItem(R.id.bookmark);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.funstory:
			startActivity(new Intent(FunStory.this, ListItem.class));
			FunStory.this.finish();
			break;
		case R.id.share:
			Intent sharingIntent = new Intent(Intent.ACTION_SEND);
			sharingIntent.setType("text/plain");
			// sharingIntent
			// .putExtra(
			// android.content.Intent.EXTRA_TEXT,
			// Html.fromHtml(funStories.get(
			// onPageChange.getCurrentPage()).getContent())
			// +
			// " \n Cười thả ga với Ứng dụng Truyện Bựa 18+ - https://play.google.com/store/apps/details?id="
			// + APP_PACKAGE);
			ComponentName name = new ComponentName(APP_PACKAGE, APP_NAME);
			sharingIntent.setComponent(name);
			startActivity(Intent.createChooser(sharingIntent, "Chia sẻ với"));
			break;
		}
		return true;
	}

	@Override
	protected void requestListItems(String svr_link, int start, int count) {
		if (isOnline()) {
			ItemListDownload itemListDownload = new ItemListDownload(this, this);
			itemListDownload.start(svr_link, start, count);
		} else {
			showNetworkDialog();
		}
	}

	@Override
	public void onDownloadFinish(ArrayList<Item> result, String svr_link,
			int start, int count) {
		if (result != null && result.size() > 0) {
			Log.e("TAG", "ok2");
			funStories = result;
			initContent();
		} else {
			if (result.size() <= 0) {
				storyArr.clear();
				store.setStoryArr(storyArr);
				if (funStories == null || funStories.size() <= 0) {
					requestListItems(CConstant.SVR_FUNSTORY_LINK, 0, itemCount);
				} else {
					initContent();
				}
			} else {
				GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
				showReconnectDialog(svr_link, start, count);
				Log.e("TAG", "lose2");
			}
		}
	}

	@Override
	public void onDownloadError(String svr_link, int start, int count) {
		GA.trackDetailView(APP_NAME + "_funStoryDownloadListError");
		showReconnectDialog(svr_link, start, count);
	}
}
